package cn.iocoder.yudao.module.infrastructure.messy.controller.app;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.URLUtil;
import cn.iocoder.yudao.framework.common.biz.config.ConfigCommonApi;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.qrcode.pojo.QrCodeDataType;
import cn.iocoder.yudao.module.api.infrastructure.social.SocialClientApi;
import cn.iocoder.yudao.module.api.infrastructure.social.dto.SocialWxQrcodeReqDTO;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "用户 App - 小程序码")
@RestController
@RequestMapping("/infra/wxacode")
@Validated
@Slf4j
public class AppWxaCodeController extends AppBaseCodeController {
    private static final String QRCODE_PAGE_CONFIG_KEY = "infrastructure.qrcode.page";
    @Resource
    private SocialClientApi socialClientApi;
    @Resource
    private ConfigCommonApi configApi;

    @Nonnull
    @Override
    protected <T extends QrCodeDataType> String generatePngAsUri(T type) {
        String wxaPage = configApi.getConfigValueByKey(QRCODE_PAGE_CONFIG_KEY);
        String wxaScene = type.toWxaScene();
        log.info("[generatePngAsUri][生成小程序码跳转页面及场景参数: {}，{}]", wxaPage, wxaScene);
        Assertions.isTrue(wxaScene.getBytes().length <= 1024, "微信小程序码场景参数长度不超过 1024 字节：" + wxaScene);
        byte[] bytes = socialClientApi.getWxaQrcode(new SocialWxQrcodeReqDTO()
                .setScene(wxaScene)
                .setPath(wxaPage)
                .setWidth(300)
                .setAutoColor(false)
                .setCheckPath(false)
                .setHyaline(false));
        if (bytes == null || bytes.length == 0) {
            return "";
        }
        return URLUtil.getDataUri("image/png", "base64", Base64.encode(bytes));
    }

}
